package com.platform.api.bzproject.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.api.bzproject.model.UserClassify;
import com.platform.api.bzproject.service.IUserClassifyService;
import com.platform.api.common.service.ByteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author guoyunfei on 2022/1/14 23:05
 * @className AntidirtJob
 * @description TODO
 * @Version 1.0
 */

@Slf4j
@Component
public class AntidirtJob {

    @Autowired
    private ByteService byteService;

    @Autowired
    private IUserClassifyService iUserClassifyService;


    @Async
    //@Scheduled(cron = "0/10 * * * * ?") //或直接指定时间间隔，例如：5秒
    @Scheduled(cron = "0 0 0/1 * * ?") //3小时执行一次
    @Transactional(rollbackFor = Exception.class)
    public void antidirt() throws IOException{
        System.out.println("AntidirtJob");

        List<UserClassify> list = iUserClassifyService.list(new QueryWrapper<UserClassify>().eq("status", 0));

        int size = list.size();

        for (int i = 0; i < size; i++) {

            JSONObject jsonObject = new JSONObject();
            JSONArray array = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("content",list.get(i).getName());
            array.add(obj);
            jsonObject.put("tasks",array);

            String antidirt = byteService.antidirt(jsonObject);

            //解析数据
            JSONObject resu = JSON.parseObject(antidirt);

            if(resu.getIntValue("code") != 401){
                JSONArray data = resu.getJSONArray("data");

                JSONObject obja = (JSONObject) data.get(0);

                JSONObject predicts = (JSONObject) obja.getJSONArray("predicts").get(0);

                if(predicts.getBoolean("hit")){
                    list.get(i).setStatus(2);
                }else{
                    list.get(i).setStatus(1);
                }
                iUserClassifyService.updateById(list.get(i));
            }

        }

    }
}
